import csv
import os

class ParseCsv:
    """解析 csv 文件"""
    
    def __init__(self, file_name) -> None:
        
        # 文件头
        self.header = {}
        # 文件数据
        self.rows = {}
        # 当前工作目录路径
        self.current = os.getcwd() + "/"
        # 读取
        self._upload(file_name)

    def _upload(self, file_name):
        """读取文件"""

        filename = self.current + file_name

        with open(file=filename) as file:
            reader = csv.reader(file)
            header_row = next(reader)
            # 设置头
            self.header = { value: index for index, value in enumerate(header_row)}
            # 设置数据
            self.rows = [row for row in reader]

    def query_columns(self, columns):
        """查询单列值"""

        datas = []
        for row in self.rows:
            data_column = {}
            
            for column in columns:
                try:
                   data_column[column] = row[self.header[column]]
                except KeyError:
                    pass
                else:
                    datas.append(data_column)
        return datas

            
        

